package tech.lq0.dreamaticvoyage.tools;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.material.Fluid;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.registries.ForgeRegistries;

public class RecipeTool {

    public static Ingredient getIngredientFromJson(JsonObject jsonObject, String key) {
        if (!jsonObject.has(key)) {
            return Ingredient.EMPTY;
        }
        JsonElement jsonElement = GsonHelper.isArrayNode(jsonObject, key) ?
                GsonHelper.getAsJsonArray(jsonObject, key) : GsonHelper.getAsJsonObject(jsonObject, key);
        return Ingredient.fromJson(jsonElement);
    }

    public static FluidStack getFluidFromJson(JsonObject jsonObject, String key) {
        if (!jsonObject.has(key)) {
            return FluidStack.EMPTY;
        }
        if (GsonHelper.isObjectNode(jsonObject, key)) {
            var obj = GsonHelper.getAsJsonObject(jsonObject, key);
            var nbt = CraftingHelper.getNBT(obj);

            CompoundTag tag = new CompoundTag();
            if (!nbt.contains("name", Tag.TAG_STRING)) {
                return FluidStack.EMPTY;
            }
            tag.putString("FluidName", nbt.getString("name"));
            tag.putInt("Amount", nbt.getInt("amount"));
            if (nbt.contains("tag", Tag.TAG_COMPOUND)) {
                tag.put("Tag", nbt.getCompound("tag"));
            }

            return FluidStack.loadFluidStackFromNBT(tag);
        } else {
            String name = GsonHelper.getAsString(jsonObject, key);
            ResourceLocation fluidName = new ResourceLocation(name);
            Fluid fluid = ForgeRegistries.FLUIDS.getValue(fluidName);
            if (fluid == null) return FluidStack.EMPTY;

            return new FluidStack(fluid, 1000);
        }
    }
}
